package com.jboost.modules.app.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.jboost.common.api.vo.Result;
import com.jboost.common.constant.enums.OpEnum;
import com.jboost.common.util.HttpRestUtils;
import com.jboost.modules.app.constant.CompanyEnum;
import com.jboost.modules.app.constant.ThirdCompanyEnum;
import com.jboost.modules.app.util.EnumUtils;
import com.jboost.modules.app.util.JwtUtil;
import com.jboost.modules.app.constant.TokenDto;
import com.jboost.modules.system.constant.ConnectEnum;
import com.jboost.modules.system.constant.DepartEnum;
import com.jboost.modules.system.entity.SysUser;
import com.jboost.modules.system.mapper.SysUserMapper;
import com.jboost.modules.system.service.ISysDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.jboost.modules.app.util.RequestUtil.httpPost;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/metronme")
@Slf4j
public class MetronomeController extends AppBaseController{




    @Autowired
    ISysDictService iSysDictService;
    @Autowired
    SysUserMapper sysUserMapper;

    @GetMapping(value = "/login")
    @ApiOperation(value = "登陆", notes = "登陆")
    public Result<String> login(@RequestParam(value = "company") String company,@RequestParam(value = "userName") String userName,@RequestParam(value = "passWord") String passWord,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException {
        List<SysUser> sysUsers =
                sysUserMapper.selectList(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getRealname, userName).eq(SysUser::getPassword, passWord));//.eq(SysUser::getCreateBy, EnumUtils.getDescByType(CompanyEnum.class,company))
        if (CollectionUtil.isEmpty(sysUsers)) {
            throw new RuntimeException("账号不存在或密码不正确");
        }
       return SSO(company,httpServletRequest,httpServletResponse);
    }

    @GetMapping(value = "/scmLogin")
    @ApiOperation(value = "scm登陆", notes = "登陆")
    public Result<Map> scmLogin(@RequestParam(value = "company") String company,@RequestParam(value = "userName") String userName,@RequestParam(value = "passWord") String passWord,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException {
        SysUser sysUser = sysUserMapper.selectOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getRealname, userName).eq(SysUser::getPassword, passWord).eq(SysUser::getThirdId, "scm"));
        if (Objects.isNull(sysUser)) {
            throw new RuntimeException("账号不存在或密码不正确");
        }
        return scmSSO(sysUser,httpServletRequest,httpServletResponse);
    }


    @GetMapping(value = "/welynkLogin")
    @ApiOperation(value = "scm登陆", notes = "登陆")
    public Result<List<SysUser>> welynkLogin(@RequestParam(value = "userName") String userName,@RequestParam(value = "passWord") String passWord,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException {
        SysUser sysUser = sysUserMapper.selectOne(Wrappers.lambdaQuery(SysUser.class)
                .eq(SysUser::getRealname, userName).eq(SysUser::getPassword, passWord).eq(SysUser::getThirdId, CompanyEnum.WELYNK.getType()));
        if (Objects.isNull(sysUser)) {
            throw new RuntimeException("账号不存在或密码不正确");
        }
        List<SysUser> sysUsers = sysUserMapper.selectByClientId(sysUser.getClientId()).stream()
                .filter(e->!Objects.equals(e.getId(),sysUser.getId())).collect(Collectors.toList());
        return Result.OK(sysUsers);
    }

    private Result<Map> scmSSO(SysUser sysUser, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        Map<String, String> params = new HashMap<>();
        params.put("username",sysUser.getRealname());
        params.put("password",sysUser.getPassword());
        String str = httpPost("http://202.105.104.158:8202/srm/mvc/services/doLogin", params);
//
        JSONObject jsonObject = JSONObject.parseObject(str);
        HashMap<String, Object> objectObjectHashMap = Maps.newHashMap();
        objectObjectHashMap.put("sessionKey",jsonObject.getString("data"));
//        Cookie cookie = new Cookie("sessionKey", jsonObject.getString("data")); // 创建Cookie对象
//        cookie.setMaxAge(3600); // 设置Cookie的过期时间，单位为秒
//        httpServletResponse.addCookie(cookie); // 将Cookie添加到响应中
//        httpServletResponse.sendRedirect("http://202.105.104.158:8202/srm");
        return Result.OK(objectObjectHashMap);
    }

    @PostMapping(value = "/push")
    @ApiOperation(value = "数据推送", notes = "数据推送")
    public Result<String> push(@RequestBody JSONObject jsonObject, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        return pushResult(jsonObject);
    }

    @PostMapping(value = "/pushScm")
    @ApiOperation(value = "数据推送", notes = "数据推送")
    public Result<String> pushScm(@RequestBody JSONObject jsonObject, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        push(jsonObject,httpServletRequest,httpServletResponse);
        pushWelynkResult(jsonObject);
        return pushScmResult(jsonObject);
    }


    private Result<String> pushWelynkResult(JSONObject jsonObject) throws IOException {
        String op = jsonObject.getString("op");

        LinkedHashMap data = (LinkedHashMap) jsonObject.get("data");
        //应用id
        String appId = (String)data.get("appId");
        //String depart = getDepartNoByName((String) data.get("depart"),appId);
        if (Objects.equals(op, OpEnum.DATA_CREATE.getOp())){
            SysUser sysUser = new SysUser();
            sysUser.setClientId((String) data.get("_id"));
            sysUser.setUsername((String) data.get("username"));
            sysUser.setRealname((String) data.get("waccount"));
//            sysUser.setPhone((String) data.get("phone"));
            sysUser.setPassword((String) data.get("wpassword"));
            sysUser.setDelFlag(0);
            sysUser.setThirdId(CompanyEnum.WELYNK.getType());
            //sysUser.setDepartIds(depart);
            sysUser.setCreateBy(appId);
            sysUserMapper.insert(sysUser);
        }
        if (Objects.equals(op,OpEnum.DATA_UPDATE.getOp())){
            SysUser userByName = sysUserMapper.selectOneByClientId((String) data.get("_id"));
            if (Objects.isNull(userByName)){
                userByName = new SysUser();
                userByName.setDelFlag(0);
                // userByName.setDepartIds(depart);
                userByName.setUsername((String) data.get("username"));
                userByName.setRealname((String) data.get("waccount"));
                userByName.setPassword((String) data.get("wpassword"));
                userByName.setClientId((String) data.get("_id"));
                sysUserMapper.insert(userByName);
            }else {
                userByName.setPassword((String) data.get("wpassword"));
                userByName.setUsername((String) data.get("wusername"));
                // userByName.setDepartIds(depart);
                userByName.setClientId((String) data.get("_id"));
                sysUserMapper.updateById(userByName);
            }
        }
        if (Objects.equals(op,OpEnum.DATA_REMOVE.getOp())){
            SysUser sysUser = new SysUser();
            sysUser.setUsername((String) data.get("username"));
            SysUser userByName = sysUserMapper.selectOneByClientId((String) data.get("_id"));
            if (Objects.nonNull(userByName)) {
                sysUserMapper.deleteWithId(userByName.getId());
            }
        }
        System.out.println(jsonObject);
        return Result.OK();
    }

    private Result<String> pushScmResult(JSONObject jsonObject) throws IOException {
        String op = jsonObject.getString("op");

        LinkedHashMap data = (LinkedHashMap) jsonObject.get("data");
        //应用id
        String appId = (String)data.get("appId");
        //String depart = getDepartNoByName((String) data.get("depart"),appId);
        if (Objects.equals(op, OpEnum.DATA_CREATE.getOp())){
            SysUser sysUser = new SysUser();
            sysUser.setClientId((String) data.get("_id"));
            sysUser.setUsername((String) data.get("username"));
            sysUser.setRealname((String) data.get("saccount"));
//            sysUser.setPhone((String) data.get("phone"));
            sysUser.setPassword((String) data.get("spassword"));
            sysUser.setDelFlag(0);
            sysUser.setThirdId(ThirdCompanyEnum.SCM.getType());
            //sysUser.setDepartIds(depart);
            sysUser.setCreateBy(appId);
            sysUserMapper.insert(sysUser);
        }
        if (Objects.equals(op,OpEnum.DATA_UPDATE.getOp())){
            SysUser userByName = sysUserMapper.selectOneByClientId((String) data.get("_id"));
            if (Objects.isNull(userByName)){
                userByName = new SysUser();
                userByName.setDelFlag(0);
               // userByName.setDepartIds(depart);
                userByName.setUsername((String) data.get("username"));
                userByName.setRealname((String) data.get("saccount"));
                userByName.setPassword((String) data.get("spassword"));
                userByName.setClientId((String) data.get("_id"));
                sysUserMapper.insert(userByName);
            }else {
                userByName.setPassword((String) data.get("spassword"));
                userByName.setUsername((String) data.get("username"));
               // userByName.setDepartIds(depart);
                userByName.setClientId((String) data.get("_id"));
                sysUserMapper.updateById(userByName);
            }
        }
        if (Objects.equals(op,OpEnum.DATA_REMOVE.getOp())){
            SysUser sysUser = new SysUser();
            sysUser.setUsername((String) data.get("username"));
            SysUser userByName = sysUserMapper.selectOneByClientId((String) data.get("_id"));
            if (Objects.nonNull(userByName)) {
                sysUserMapper.deleteWithId(userByName.getId());
            }
        }
        System.out.println(jsonObject);
        return Result.OK();
    }

    public Result<String> getStringResult(JSONObject jsonObject, String op) throws IOException {
        LinkedHashMap data = (LinkedHashMap) jsonObject.get("data");
        //应用id
        String appId = (String)data.get("appId");
        Map<String,Object> map = new HashMap<>();
        if (Objects.equals(op,OpEnum.DATA_CREATE.getOp())){
            map.put("name",(String) data.get("name"));
            map.put("parent_no", data.get("parent_no"));
            map.put("dept_no", data.get("dept_no"));
            String post = HttpRestUtils.post(DepartEnum.ADD.getUrl(), map, getApiKeyHeaders(appId));
            cache.put((String) data.get("_id"),(String) data.get("dept_no"));
        }
        if (Objects.equals(op,OpEnum.DATA_UPDATE.getOp())){
            map.put("name",(String) data.get("name"));
            map.put("parent_no", data.get("parent_no"));
            map.put("dept_no", data.get("dept_no"));
            HttpRestUtils.post(DepartEnum.UPDATE.getUrl(), map,getApiKeyHeaders(appId));
            cache.put((String) data.get("_id"),(String) data.get("dept_no"));
        }
        if (Objects.equals(op,OpEnum.DATA_REMOVE.getOp())){
            map.put("dept_no",cache.get((String) data.get("_id")));
            HttpRestUtils.post(DepartEnum.DELETE.getUrl(), map,getApiKeyHeaders(appId));
        }
        System.out.println(jsonObject);
        return Result.OK();
    }

    @PostMapping(value = "/departPush")
    @ApiOperation(value = "部门数据推送", notes = "部门数据推送")
    public Result<String> departPush(@RequestBody JSONObject jsonObject, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        String op = jsonObject.getString("op");
        return getStringResult(jsonObject,op);
    }


    @GetMapping(value = "/sso")
    @ApiOperation(value = "app节拍器、调音器", notes = "app节拍器、调音器")
    public Result<String> SSO(String company, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException {
        CompanyEnum enumByType = (CompanyEnum) EnumUtils.getEnumByType(CompanyEnum.class, company);
        String ACS = enumByType.getAcs();//"https://www.jiandaoyun.com/sso/custom/62f26217580e98000794d37d/acs";
        String SECRET = enumByType.getSecret();//"uEZQJm9QujTUtcyV7afujAoR";
        String userName = servletRequest.getParameter("userName");;
        TokenDto tokenDto = new TokenDto();
        tokenDto.setUsername(userName);
        tokenDto.setIss(enumByType.getDesc());
        Map<String, Object> map =
                BeanUtil.beanToMap(tokenDto,false,true);
        String jwt = JwtUtil.createJWT(map,SECRET);
        String response = ACS + "?response=" + jwt;
//        servletResponse.sendRedirect(response);
        return Result.OK(response);
    }


}
